//
//  UIView+AD.swift
//  ADKit
//
//  Created by Adoma on 2023/12/26.
//

import UIKit

public extension UIView {
    
    /// by ADKit
    convenience init(backgroundColor: UIColor?) {
        self.init(frame: .zero)
        self.backgroundColor = backgroundColor
    }

    var ad_viewController: UIViewController? {
        var view: UIView? = self
        while view != nil {
            if let next = view?.next, next is UIViewController {
                return next as? UIViewController
            }
            view = view?.superview
            
        }
        return nil
    }
    
    func ad_rounded(cornerRadius: CGFloat, width:CGFloat = 0, border: UIColor? = nil, mask: CACornerMask = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]) {
        self.layer.cornerRadius = cornerRadius
        self.layer.borderWidth = width
        self.layer.borderColor = border?.cgColor
        self.layer.maskedCorners = mask
        self.layer.masksToBounds = true
    }
    
    func removeAllSubviews() {
        subviews.forEach {
            $0.removeFromSuperview()
        }
    }
}

public extension UIView {
 
    var x: CGFloat { 
        get {
            return frame.origin.x
        }
        set {
            frame.origin.x = newValue
        }
    }
    
    var y: CGFloat {
        get {
            return frame.origin.y
        }
        set {
            frame.origin.y = newValue
        }
    }
    
    var width: CGFloat {
        get {
            return frame.size.width
        }
        set {
            frame.size.width = newValue
        }
    }
    
    var height: CGFloat {
        get {
            return frame.size.height
        }
        set {
            frame.size.height = newValue
        }
    }
    
}

public extension CGRect {
    
    var ad_center: CGPoint {
        .init(x: self.origin.x + self.size.width * 0.5, y: self.origin.y + self.size.height * 0.5)
    }
}
